<template>
  <div>
    <MainNavBar>
      <template #center-name> 参赛详情 </template>
    </MainNavBar>
    <van-pull-refresh
      v-model="isLoading"
      success-text="刷新成功"
      @refresh="onRefresh"
    >
      <div class="content_C">
        <div class="content">
          <!-- 左侧条状 -->
          <div class="content_left">
            <!-- 一阶段 -->
            <div class="circular">
              <div class="grey"></div>
              <div class="white"></div>
            </div>
            <div class="line one"></div>
            <!-- 二阶段 -->
            <div class="circular">
              <div class="grey"></div>
              <div class="white"></div>
            </div>
            <div class="two" :style="{height}"></div>
            <!-- 三阶段 -->
            <div class="circular">
              <div class="grey"></div>
              <div class="white"></div>
            </div>
            <div class="line three"></div>
          </div>
          <div class="content_right">
            <!-- 选手信息卡片 -->
            <div class="right_a">
              <div class="right_a_top">
                <div class="number"><img src="http://qnticao.laigl.com/vue/10b505e068bc12e8c7e80c317e9a9a9.png" alt=""></div>
                <div class="title">报名信息</div>
              </div>
              <div class="userinfo">
                <div class="user_img">
                  <!-- <img src="http://qnticao.laigl.com/vue/user.jpg" alt="" /> -->
                  <img :src="userinfo.head_img" alt="头像" />
                </div>
                <div class="user_info">
                  <div class="user_name">
                    {{ userinfo.sign_name
                    }}<span>{{ userinfo.sex == 0 ? "(男)" : "(女)" }}</span>
                  </div>
                  <div class="user_adress">{{ userinfo.city }}</div>
                  <div class="user_card">{{ idcard }}</div>
                  <div class="user_grade">
                   {{userinfo.compet_id == 1?'通级赛等级：' + getsexlevel(userinfo) : '亲子赛等级：'+ getlevel(userinfo.level)}}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 上传视频卡片  -->
            <div class="right_b">
              <div class="right_b_top">
                <div class="number"><img src="http://qnticao.laigl.com/vue/c91eabeac4600b0f264925d4391e38d.png" alt=""></div>
                <div class="title">视频上传</div>
              </div>
              <div class="itme" v-for="(compent,index) in compent_list" :key='compent'>
                <div class="project">{{compent}}：</div>  
                <div class="userinfo uplode_video">
                <div class="video" @click="upVideo(index)" >
                  <div class="video_tip"  v-if="video_url[index]=='' && percentage[index]==0">
                    <van-uploader style="display:none" :ref="'vant'+index" accept="video/*" :after-read="getVideo">
                      <van-button  type="primary">上传文件</van-button>
                    </van-uploader>
                    <div>
                      <img src="http://qnticao.laigl.com/vue/uplode_video.png" alt="" />
                    </div>
                    <div>点击上传</div>
                  </div>
                  <div class="wait" v-else-if="percentage[index]!=0">正在上传视频,请稍等</div>
                  <div v-else-if="video_url[index]!==''">
                    <video
                      id="video"
                     :poster="posterimg[index]"
                     :src="video_url[index]"
                      controls
                      x5-playsinline
                      playsinline
                      webkit-playsinline
                      preload="auto"
                    ></video>
                  </div>
                 
                </div>
              <van-progress color="#0054a6" :percentage="percentage[index]" v-if="percentage[index]!=0" />
                <div class="uplode_tip">
                  请上传60s~100s内的比赛视频，视频一经上传不可改，待评审结果公布且为“未通级”时方可再次上传新视频补考。
                </div>
              </div>
              </div>
              
              
            </div>

            <!-- 查看结果卡片 -->
            <div class="right_c">
              <div class="right_c_top">
                <div class="number"><img src="http://qnticao.laigl.com/vue/f4191e3ca1a5f84f5c202b24c38ccdf.png" alt=""></div>
                <div class="title">结果公布</div>
              </div>
              <div class="userinfo">
                <!-- 结果等待公布 -->
                <div class="state_a" v-if="state == 0">
                  <img src="http://qnticao.laigl.com/vue/marshalling_3.png" alt="" />
                  <div class="blur"></div>
                  <div>{{setstartTime(result_start,result_end)}}公布结果</div>
                </div>
                <!-- 未通过，补考 -->
                <div class="state_b" v-else-if="state == 1" @click="onceAgain">
                  <div class="sorry">抱歉，还差一点点~</div>
                  <img src="http://qnticao.laigl.com/vue/marshalling_4.png" alt="" />
                  <div class="but">再来一次</div>
                </div>
                <!-- 通过，查看证书 -->
                <div class="state_c" @click="goMycertificate()" v-else>
                  <div class="congratulations">
                    恭喜<span
                      style="padding-left: 0.8vw; padding-right: 0.8vw"
                      >{{ userinfo.sign_name }}</span
                    >：
                  </div>
                  <div class="level">
                     {{userinfo.compet_id == 1?'通过通级赛等级：' + getsexlevel(userinfo) : '通过亲子赛等级：'+ getlevel(userinfo.level)}}
                    <!-- 通过通级赛{{ userinfo.sex == 0 ? "男" : "女" }}子{{
                      userinfo.level
                    }}级 -->
                  </div>
                  <div class="Certificate" v-if="userinfo.compet_id == 1">查看证书&nbsp;></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import MainNavBar from "@/components/common/nav/MainNavBar.vue";
import { request } from "../../network/request";
import { Toast, Dialog} from "vant";
import * as qiniu from "qiniu-js";
import { nextTick } from 'vue';

export default {
  data() {
    return {
      isLoading: false,
      idcard: "",
      state: 0,
      file: [],
      video_url: [],
      duration: "", //视频时长
      userinfo: "",
      is_again: 0,
      qntoken: "",
      currentIndex:0,
      progress:false,//进度条
      percentage:[] ,
      posterimg:[],
      video_key:[],//上传七牛后返回给后端
      compet_id:"",
      level_id:"",//等级id
      result_start:"",
      result_end:"",
      compent_list:[],
      height:"",
      quUrl:'http://qnticao.laigl.com/'
      
    };
  },
  computed: {
      
  },
  mounted() {
    this.getUserinfo();
    this.state = this.$route.query.state;
    if(this.$route.query.sex==0){
        this.compent_list = ['自由体操','山羊（无环鞍马）','吊环','跳马','双杠',"单杠","蹦床"]

    }else if(this.$route.query.sex==1){
        this.compent_list = ['跳马','高低杠','平衡木','自由体操','蹦床']
    }
    console.log(this.$route.sex);
    console.log(this.compent_list);
    const length = this.compent_list.length;
    let originArr1 = new Array(length).fill("");
    let originArr2 = new Array(length).fill("");
    let originArr3 = new Array(length).fill("");
    this.video_url = originArr1;
    this.posterimg =  originArr2,
    this.video_key =  originArr3,
    this.percentage = new Array(length).fill(0);

    this.getQiniuToken();//获取七牛token
    this.getHeight()
         window.scrollTo(0, 0);
  },
  methods: {
    getHeight(){
          nextTick(()=>{
              console.log(window.getComputedStyle(document.querySelector(".right_b")).height);
              this.height = window.getComputedStyle(document.querySelector(".right_b")).height;
          })
      },
    getsexlevel(item){
      if (item.level<3) {
          return item.level+'级'
      }
      else{
        if( item.sex == 0){
          return '男子'+item.level+'级'
        }else{
          return '女子' + item.level + '级'
        }
      }
    },
    getsex(sex){
      if(sex==0){
        return '男'
      }
      else{
        return '女'
      }
    },
    // 获取等级
    getlevel(level){
      switch (level) {
        case 1:
          return '初级'
        case 2:
          return '中级'
        case 3:
          return '高级'    
        default:
          break;
      }
    },
    // 获取证书时间
    async getLevels(){
      try {
        const lv = await request({
          url:'/v1/index/getLevels',
          data:{
            id:this.level_id,
          }
        })
        if (lv.code == 200) {
          this.result_start= lv.data.rows[0].result_start_time,
          this.result_end = lv.data.rows[0].result_end_time
        }
      } catch (error) {
        Toast(error.msg)
      }
    },
    // 结果发布时间
    setstartTime(start_time,end_time){
      let M = start_time.substring(5,7)
      let d = start_time.substring(8)
      let end_d = end_time.substring(8)
      return M + '月' + d +'日' + '——' + end_d +'日'
    },
    getVideo(e){
      console.log(e.file);
      this.file[this.currentIndex]=e.file
      this.upload(e.file)
    },
    //初始提示
    upVideo(index){
        if (this.progress) {
            Toast('正在上传，请稍后')
            return
        }
       this.currentIndex = index
       this.$refs["vant"+index].chooseFile();
       return
      Dialog.confirm({
        title: "提示",
        message: "请上传70s内的视频文件，视频一经上传不可更改",
      })
        .then(() => {
          // document.querySelector(".uplode").click();
         
        })
        .catch(() => {
          return;
        });
    },
    // 跳转查看证书
    goMycertificate() {
      if(this.$route.query.is_general == 2){
        return
      }
      this.$router.push({
        path: "/mycertificate",
      });
    },
    updatevideo(e) {
      this.file = e.target.files[0];
      var url = URL.createObjectURL(this.file);
      let audioElement = new Audio(url);
      this.upload(this.file);//上传视频至七牛云

      // 判断视频时长
      // audioElement.addEventListener("loadedmetadata", () => {
      //   let duration = audioElement.duration;
      //   if (duration > 101) {
      //     console.log(this.duration);
      //     Toast("上传时间超过100秒,请重新上传");
      //     return;
      //   }
      //   this.upload(this.file);//上传视频至七牛云
      // });
    },
    // 上传视频后发送请求到服务器
    async uploadvideo() {
      try {
      var formData = new FormData();
      formData.append("sign_id", this.$route.query.sign_id);
      formData.append("token", sessionStorage.getItem("token"));
      formData.append("is_again", this.is_again);
      if(this.$route.query.sex==0){
        formData.append("mvideo"+(this.currentIndex+1),  'http://qnticao.laigl.com/' + this.video_key[this.currentIndex]);
      }else{
        formData.append("gvideo"+(this.currentIndex+1), 'http://qnticao.laigl.com/' + this.video_key[this.currentIndex]);
      }
      formData.append("status", 1);
    //   try {
        const data = await request({
        url: "/v1/ucenter/sign_detail",
        data: formData,
          });
          //  let temp3 = [];
          // let temp4 = [];
          if (data.code == 200) {
            this.video_url[this.currentIndex] = URL.createObjectURL(this.file[this.currentIndex]);
            // this.video_url[this.currentIndex] ='http://qnticao.laigl.com/' +  this.video_key[this.currentIndex]
            this.posterimg[this.currentIndex] = 'http://qnticao.laigl.com/' +  this.video_key[this.currentIndex] + '?vframe/jpg/offset/8/w/280/h/168';
            this.progress = false
            this.percentage[this.currentIndex] = 0
            this.state = 0;
            Toast.success('比赛视频已成功上传！');
          }
      }
       catch (error) {
         this.uploadvideo()
        // this.progress = false
        // this.percentage[this.currentIndex] = 0
        // Toast.fail('请再来一次')
        //  this.state = 1;
        //  return
      }
    },
    // 下拉更新
    onRefresh() {
      setTimeout(() => {
         this.getUserinfo()
      }, 1000);
    },
    // 未通过重新上传视频
    onceAgain() {
      Dialog.confirm({
        title: "提示",
        message: "是否重新上传比赛视频",
      })
        .then(() => {
          this.video_url = new Array(this.compent_list.length).fill("")
          this.is_again = 1//补考
          this.state = 0
        //   this.progress = false
        //   document.querySelector(".uplode").click();
        }).catch(() => {
          return;
        });
    },
    // 获取上传凭证
    async getQiniuToken() {
      const qn = await request({
        url: "/v1/upload/getToken",
      });
      if (qn.code == 2000) {
        this.qntoken = qn.data;
        console.log(this.qntoken);
      }
    },
// 生成随机视频名称
    randomWord(randomFlag, min, max) {
    var str = "",
      range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
      let  pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
    },
    // 上传视频至七牛云
    upload(file) {
      this.progress = true
      return new Promise((resolve, reject) => {
        var uptoken = this.qntoken;
        let key = this.randomWord(false,20)
        var config = {
          useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
          region: qiniu.region.z0, //选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域。  我这里是华东区
          domain: "https://qnticao.laigl.com", //配置好的七牛云域名  如   https://cdn.qniyun.com/
          max_file_size:"100mb",
          chunkSize: 3, //每个分片的大小，单位mb，默认值3
          forceDirect: true, //直传还是断点续传方式，true为直传
        };
        var putExtra = {
          fname: file.name, //文件原始文件名
          params: {}, //放置自定义变量
          // mimeType: "video/mp4", //限制上传文件类型
          mimeType: [] || null, //限制上传文件类型
          // ...config,
        };
        var observable = qiniu.upload(file, key, uptoken, putExtra, config);
        observable.subscribe({
          next: (result) => {
            //主要用来展示进度
            this.percentage[this.currentIndex] = Math.floor(result.total.percent)
          },
          error: (err) => {
            //上传错误后触发
            console.log(err);
            Toast.fail('比赛视频上传失败，请重新上传！');
            this.progress = false
            this.percentage[this.currentIndex] = 0
            this.video_url[this.currentIndex] = ""
            return
            reject(err);
          },
          complete: (result) => {
            //上传成功后触发。包含文件地址。
            this.video_key[this.currentIndex] = result.key;
            this.uploadvideo()//发送后端请求
            resolve(result);
          },
        });
      });
      // });
    },
    // 初始化页面数据
    async getUserinfo() {
      try {
        const res = await request({
          url: "/v1/ucenter/sign_detail",
          data: {
            sign_id: this.$route.query.sign_id,
            token: sessionStorage.getItem("token"),
             is_again:0,
             video:"",
             status:this.$route.query.status
          },
        });
        if (res.code == 200) {
          this.userinfo = res.data.data;
         for (let i = 0; i < this.video_url.length; i++) {
             if(this.$route.query.sex==1 && res.data.data['gvideo'+(i+1)]){
             this.video_url[i] =res.data.data['gvideo'+(i+1)] ;
              this.posterimg[i] =res.data.data['gvideo'+(i+1)] + '?vframe/jpg/offset/8/w/280/h/168' 
             }else if(this.$route.query.sex==0 && res.data.data['mvideo'+(i+1)]){
             this.video_url[i] = res.data.data['mvideo'+(i+1)];
             this.posterimg[i] = res.data.data['mvideo'+(i+1)] + '?vframe/jpg/offset/8/w/280/h/168' 
             }
         }
          this.idcard = res.data.data.id_card;
          this.compet_id = res.data.data.compet_id;
          this.level_id = res.data.data.level_id;
        //   this.posterimg = res.data.data.video + '?vframe/jpg/offset/8/w/280/h/168' 
          // 身份号中间加密

          let star = ""; //存放名字中间的*
          for (var i = 0; i < this.idcard.length - 10; i++) {
            star = star + "*";
          }
          this.idcard =
            this.idcard.substring(0, 6) +
            star +
            this.idcard.substring(this.idcard.length - 4, this.idcard.length);
            this.getLevels()
            this.isLoading=false
        }
      } catch (error) {}
    },
  },
  components: {
    MainNavBar,
  },
};
</script>

<style lang="less" scoped>
.wait{
  font-size: 5.867vw;
  width: 100%;
  text-align: center;
  line-height: 44.8vw;
}
video {
  width: 74.667vw;
  height: 44.8vw;
  border-radius: 2.667vw;
}
.number {
  z-index: 4;
  position: absolute;
  width: 27.733vw;
  top: -16vw;
  left: 0;
  overflow-wrap: break-word;
  color: rgba(255, 255, 255, 0.19);
  font-size: 21.333vw;
  // transform: skew(-20deg);
  line-height: 27.733vw;
  font-weight: 600;
  img{
    width: 21.333vw;
    height: 13.333vw;
  }
}
.title {
  font-size: 5.6vw;
  line-height: 5.6vw;
  font-weight: 600;
  color: white;
  padding-bottom: 5.333vw;
//   position: absolute;
//   top: 0;
//   left: 0;
//   z-index: 5;
}
.userinfo {
  width: 74.667vw;
  background: #fff;
  padding: 3.2vw 2.667vw;
  border-radius: 2.667vw;
  display: flex;
}
.content {
  width: 89.333vw;
  margin: 0 auto;
  margin-top: 18.667vw;
  display: flex;
  .content_left {
    display: flex;
    height: 100%;
    width: 5.867vw;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-top: 0.533vw;
    .circular {
      position: relative;
      display: flex;
      .grey {
        width: 4.533vw;
        height: 4.533vw;
        border-radius: 50%;
        background-color: #82abd3;
      }
      .white {
        width: 4.533vw;
        height: 4.533vw;
        border-radius: 50%;
        background-color: #f2f6fa;
        position: absolute;
        left: 1.067vw;
      }
    }
    .line {
      width: 0.533vw;
      height: 62.933vw;
      background-color: #a9c5e0;
      margin-left: 0.533vw;
    }
    .two {
    //   height: 598.267vw;
    width: 0.533vw;
     background-color: #a9c5e0;
      margin-left: 0.533vw;
      padding-bottom: 2.667vw;
    }
    .three {
      height: 0;
    }
  }
  .content_right {
    flex: 1;
    // display: flex;
    // flex-direction: column;
    margin-left: 2.667vw;
    position: relative;
    .right_a {
        position: relative;
        margin-bottom: 18vw;
 
    }
    .userinfo {
      .user_img {
        width: 22.933vw;
        height: 32.267vw;
        img {
          width: 22.933vw;
          height: 32.267vw;
          border-radius: 1.867vw;
        }
      }
      .user_info {
        margin-left: 3.2vw;
        flex: 1;
        .user_name {
          color: #000;
          height: 6.667vw;
          font-size: 4.267vw;
          line-height: 6.667vw;
          font-weight: 600;
          span {
            color: #D9DDE7;
            display: inline-block;
            font-size: 3.2vw;
            line-height: 6.667vw;
            font-weight: 100;
            height: 6.667vw;
            margin-left: 1.333vw;
          }
        }
        .user_adress {
          color: #D9DDE7;
          height: 6.667vw;
          font-size: 3.733vw;
          line-height: 6.667vw;
          font-size: 3.733vw;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 48.533vw;
        }
        .user_card {
          color: #D9DDE7;
          height: 6.667vw;
          font-size: 3.733vw;
          line-height: 6.667vw;
        }
        .user_grade {
          font-size: 3.733vw;
          color: rgba(10, 36, 99, 1);
          margin-top: 6.667vw;
        }
      }
    }
    .right_b {
      position: relative;
      padding-bottom: 18vw;
      box-sizing: border-box;
      .itme{
        margin-bottom: 6.333vw;  
      }
       
    //   top: 67.2vw;
    //   left: 0;
      .right_b_top {
        margin-top: 8vw;
        width: 29.333vw;
      }
      .project{
          color: #fff;
          font-size: 4.267vw;
          line-height: 8vw;
        //   margin-top: 6.333vw;
      }
      .uplode_video {
        flex-direction: column;
        .video {
          width: 74.667vw;
          height: 44.8vw;
          margin: 0 auto;
          border-radius: 2.667vw;
          background-color: #f9f9f9;
          .video_tip {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #D2D7E3;
          }
        }
        .uplode_tip {
          margin-top: 1.867vw;
          color: rgba(252, 207, 0, 1);
          font-size: 4.2vw;
          line-height: 5.2vw;
          width: 70.4vw;
        }
      }
    }
    .right_c {
      position: relative;
      padding-bottom: 18vw;
    //   top: 670vw;
    //   left: 0;
      .right_c_top {
        margin-top: 8vw;
        width: 29.333vw;
      }
      //   状态a
      .state_a {
        width: 100%;
        height: 67.733vw;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        color: #ccc;
        font-size: 4.2vw;
        line-height: 4.2vw;
        position: relative;
        .blur{
            position: absolute;
            left: 50%;
            bottom: 39%;
            transform: translate3d(-50%,-50%,0);
            width: 18.933vw;
            height: 3.467vw;
            background: #CED3E0;
            filter: blur(2.667vw);
            margin-bottom:2.667vw
        }
        img {
          width: 24vw;
          height: 12vw;
          align-self: center;
          margin-bottom: 6.667vw;
        //   box-shadow: 0px 8px 0px 0px rgba(211, 22, 22, 0.19);
        }
      }
      //   状态b
      .state_b {
        width: 100%;
        height: 67.733vw;
        display: flex;
        flex-direction: column;
        text-align: center;
        .sorry {
          text-align: left;
          font-weight: 600;
          font-size: 4.267vw;
          line-height: 5.333vw;
          margin-left: 0.8vw;
          margin-bottom: 1.333vw;
        }
        img {
          width: 63.733vw;
          height: 43.733vw;
          align-self: center;
          margin-bottom: 2.667vw;
          color: #ccc;
          box-shadow: 0vw 1.6vw 1.6vw #ced3e0;
        }
        .but {
          width: 70.933vw;
          margin: 0 auto;
          height: 12.8vw;
          font-size: 4.267vw;
          font-weight: 500;
          line-height: 12.8vw;
          border-radius: 6.4vw;
          color: #fff;
          background-color: #0054a6;
        }
      }
      .state_c {
        width: 100%;
        height: 67.733vw;
        background: url("http://qnticao.laigl.com/vue/marshalling_7.png");
        background-size: 100% 100%;
        .congratulations {
          font-weight: 600;
          font-size: 4.8vw;
          font-family: PingFangSC-Semibold;
          margin-bottom: 2.667vw;
          span {
            display: inline-block;
            border-bottom: solid 2px #000;
          }
        }
        .level {
          font-size: 4.267vw;
          margin-left: 9.333vw;
          margin-bottom: 48.333vw;
        }
        .Certificate {
          width: 100%;
          height: 6.667vw;
          text-align: center;
          line-height: 6.667vw;
          color: #0054a6;
          font-size: 4.2vw;
        }
      }
    }
  }
}
</style>
